package com.mt.repair.service.repairManagement.impl;

import com.mt.repair.dao.repairManagement.FeedbackDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.repair.entity.repairManagement.Feedback;
import com.mt.repair.service.repairManagement.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class FeedbackServiceBean extends BaseService implements FeedbackService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private FeedbackDao feedbackDao;

	@Resource
	private RedisTemplate<String, List<Feedback>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询维修评价集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findFeedbacks(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindFeedbacks(pageDTO);
		List<Feedback> feedbackDTOS = this.feedbackDao.findFeedbacks(pageDTO);
		Long totalCount = this.feedbackDao.findFeedbackTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(feedbackDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部维修评价集合
	 *
	 */
	@Override
	public List<Feedback> findAllFeedbacks(){
		return this.feedbackDao.findAllFeedbacks();
	}

	/**
	 * 查询所有维修评价集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Feedback> findAllFeedbacksWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllFeedbacksWithIdName();
		return this.feedbackDao.findAllFeedbacksWithIdName();
	}

	/**
	 * 根据名称查询维修评价集合(只提取ID 和 Name)
	 *
	 * @param feedbackName 名称
	 */
	@Override
	public List<Feedback> findFeedbacksWithIdNameByName(String feedbackName){
		//TODO:请在此校验参数的合法性
		this.validateFindFeedbacksWithIdNameByName(feedbackName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Feedback_where_feedbackName_" + feedbackName);
		List<Feedback> feedbacks = new ArrayList<>();
		if (keys.isEmpty()) {
		feedbacks = this.feedbackDao.findFeedbacksWithIdNameByName(feedbackName);
		redisTemplate.opsForValue().set("searchData:Feedback_where_feedbackName_" + feedbackName, feedbacks, 30, TimeUnit.DAYS);
		} else {
		feedbacks = redisTemplate.opsForValue().get("searchData:Feedback_where_feedbackName_" + feedbackName);
		}
		return feedbacks;
	}

	/**
	 * 根据ID查询指定的维修评价(只提取ID 和 Name)
	 *
	 * @param feedbackId Id
	 */
	@Override
	public Feedback findFeedbacksWithIdNameById(Long feedbackId){
		//TODO:请在此校验参数的合法性
		this.validateFindFeedbacksWithIdNameById(feedbackId);
		return this.feedbackDao.findFeedbacksWithIdNameById(feedbackId);
	}

	/**
	 * 根据ID查询指定的维修评价
	 *
	 * @param feedbackId Id
	 */
	@Override
	public Feedback findFeedback(Long feedbackId){
		//TODO:请在此校验参数的合法性
		this.validateFindFeedback(feedbackId);
		return this.feedbackDao.findFeedback(feedbackId);
	}

	/**
	 * 根据ID查询指定的维修评价(包含外键)
	 *
	 * @param feedbackId Id
	 */
	@Override
	public Feedback findFeedbackWithForeignName(Long feedbackId){
		//TODO:请在此校验参数的合法性
		this.validateFindFeedbackWithForeignName(feedbackId);
		return this.feedbackDao.findFeedbackWithForeignName(feedbackId);
	}

	/**
	 * 新增维修评价
	 *
	 * @param feedback 实体对象
	 */
	@Override
	public Feedback saveFeedback(Feedback feedback){
		//TODO:请在此校验参数的合法性
		this.validateSaveFeedback(feedback);
		//TODO:填充公共参数
		this.setSavePulicColumns(feedback);
		Long rows = this.feedbackDao.saveFeedback(feedback);
		if(rows != 1)
		{
			String error = "新增保存维修评价出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return feedback;
	}

	/**
	 * 更新维修评价
	 *
	 * @param feedback 实体对象
	 */
	@Override
	public Feedback updateFeedback(Feedback feedback){
		//TODO:请在此校验参数的合法性
		this.validateUpdateFeedback(feedback);
		Long rows = this.feedbackDao.updateFeedback(feedback);
		if(rows != 1)
		{
			String error = "修改保存维修评价出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return feedback;
	}

	/**
	 * 根据ID删除维修评价
	 *
	 * @param feedbackId ID
	 */
	@Override
	public void deleteFeedback(Long feedbackId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteFeedback(feedbackId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Feedback.class, feedbackId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.feedbackDao.deleteFeedback(feedbackId);
		if(rows != 1){
			String error = "删除维修评价出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindFeedbacks(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateFindFeedbacksWithIdNameByName(String feedbackName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}


	private void validateFindAllFeedbacksWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateFindFeedbacksWithIdNameById(Long feedbackId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateFindFeedback(Long feedbackId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateFindFeedbackWithForeignName(Long feedbackId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateSaveFeedback(Feedback feedback) {
	//不为空判断
	if (feedback.getEid() != null || feedback.getCreatorId() != null || feedback.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateUpdateFeedback(Feedback feedback) {
	//不为空判断
	if (feedback.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.feedbackDao.findFeedbackTotalCount(PageDTO.create(Feedback.FIELD_ID, feedback.getEid())) == 0) {
	throw new BusinessException("修改的维修评价 " + feedback.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	private void validateDeleteFeedback(Long feedbackId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFeedback()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
